<?php

/**
 * @file SendEmail
 * @author garypradoruiz <garypradoruiz@gmail.com>
 * @link mailto:garypradoruiz@gmail.com
 * @copyleft 2012 garypradoruiz
 * @license GPL
 * @version 1
 */
class Amz_Resource_SendEmail {

    public function sendEmail($id_orden = 0, $type = 0) { // enviar el id_orden , Type (New Orden = 0 Update Orden = 1 Deny Orden = 2)
        // list emails for send
        $toMails = $this->getEmailDepartamentClientInOrder($id_orden);

        $orden = $this->getDataOrdenId($id_orden);
        if ($orden != null) {
            $smtpServer = 'mail.velcro-lab.com';
            $username = 'admpro@velcro-lab.com';
            $password = 'admpro';
            
            $config = array('ssl' => 'tls',
                'auth' => 'login',
                'username' => $username,
                'password' => $password);

            $transport = new Zend_Mail_Transport_Smtp($smtpServer, $config);
            
//            $config = array('smtp' => 'mail.velcro-lab.com');
//            $transport = new Zend_Mail_Transport_Smtp('mail.velcro-lab.com', $config);
//
//            // Set From & Reply-To address and name for all emails to send.
            Zend_Mail::setDefaultFrom('admpro@velcro-lab.com', 'Seguimiento Proyectos');
            // create view object
            $html = new Zend_View();
            $html->setScriptPath(APPLICATION_PATH . '/modules/orden/views/emails/');
            $html->assign('orden', $orden);

            $request = Zend_Controller_Front::getInstance()->getRequest();
            //$url = $request->getScheme() . '://' . $request->getHttpHost() . '';
            $url = $request->getScheme() . '://' . $request->getHttpHost() . '/capataz';
            // Loop through messages
            foreach ($toMails as $to) {
                $html->assign('name', $to['name']);

                switch ($type) {
                    case 'NUEVA_ORDEN_CLIENTE':
                        if ($to['type_user'] == 'DEPARTAMENT') {
                            $html->assign('link', $url . '/orden/orden/edit-orden/id/' . $id_orden);
                        } else {
                            $html->assign('link', $url . '/orden/index/view-detail-orden/id/' . $id_orden);
                        }
                        $bodyText = $html->render('new-orden.phtml');
                        $subject = 'Orden Nueva' . ' / ' . $orden->code;
                        break;
                    case 'CLIENT_EDIT_ORDEN':
                        if ($to['type_user'] == 'DEPARTAMENT') {
                            $html->assign('link', $url . '/orden/orden/edit-orden/id/' . $id_orden);
                        } else {
                            $html->assign('link', $url . '/orden/index/view-detail-orden/id/' . $id_orden);
                        }
                        $bodyText = $html->render('change-orden.phtml');
                        $subject = 'Orden Antigua Modificada' . ' / ' . $orden->code;
                        break;
                    case 'ORDEN_DENY':
                        if ($to['type_user'] == 'DEPARTAMENT') {
                            $html->assign('link', $url . '/orden/orden/view-detail-orden/id/' . $id_orden);
                        } else {
                            $html->assign('link', $url . '/orden/index/edit-orden/id/' . $id_orden);
                        }
                        $bodyText = $html->render('deny-orden.phtml');
                        $subject = 'Mas Informacion para la orden ' . ' / ' . $orden->code;
                        break;
                    case 'ORDEN_ACCEPT':
                        if ($to['type_user'] == 'DEPARTAMENT') {
                            $html->assign('link', $url . '/orden/orden/view-detail-orden/id/' . $id_orden);
                        } else {
                            $html->assign('link', $url . '/orden/index/view-detail-orden/id/' . $id_orden);
                        }
                        $bodyText = $html->render('orden-accept.phtml');
                        $subject = 'Orden Aceptada' . ' / ' . $orden->code;
                        break;
                    case 'ORDEN_CLIENT_REVIEW': // cliente reviso la orden
                        if ($to['type_user'] == 'DEPARTAMENT') {
                            $html->assign('link', $url . '/orden/orden/view-detail-orden/id/' . $id_orden);
                        } else {
                            $html->assign('link', $url . '/orden/index/view-detail-orden/id/' . $id_orden);
                        }
                        $html->assign('title_email', "Un trabajo de la orden esta siendo revisada por el cliente");
                        $bodyText = $html->render('update-status.phtml');
                        $subject = 'Cliente revisando trabajo - Orden: ' . ' / ' . $orden->code;
                        break;
                    case 'ORDEN_CLIENT_REVISED': // cliente reviso la orden
                        if ($to['type_user'] == 'DEPARTAMENT') {
                            $html->assign('link', $url . '/orden/orden/view-detail-orden/id/' . $id_orden);
                        } else {
                            $html->assign('link', $url . '/orden/index/view-detail-orden/id/' . $id_orden);
                        }
                        $html->assign('title_email', "Un trabajo requiere cambios.");
                        $bodyText = $html->render('update-status.phtml');
                        $subject = 'Cambios para un trabajo - Orden: ' . ' / ' . $orden->code;
                        break;
                    case 'ORDEN_CLIENT_COMPLETE': // cliente reviso la orden
                        if ($to['type_user'] == 'DEPARTAMENT') {
                            $html->assign('link', $url . '/orden/orden/view-detail-orden/id/' . $id_orden);
                        } else {
                            $html->assign('link', $url . '/orden/index/view-detail-orden/id/' . $id_orden);
                        }
                        $html->assign('title_email', "Un trabajo fue aprobado por el cliente");
                        $bodyText = $html->render('update-status.phtml');
                        $subject = 'Traabjo aprobado - Orden: ' . ' / ' . $orden->code;
                        break;
                    case 'ORDEN_ATHOS_REVIEW': // cliente reviso la orden
                        if ($to['type_user'] == 'DEPARTAMENT') {
                            $html->assign('link', $url . '/orden/orden/view-detail-orden/id/' . $id_orden);
                        } else {
                            $html->assign('link', $url . '/orden/index/view-detail-orden/id/' . $id_orden);
                        }
                        $html->assign('title_email', "Trabajo pendiente a revisar por el cliente");
                        $bodyText = $html->render('update-status.phtml');
                        $subject = 'Trabajo pendiente a revision - Orden: ' . ' / ' . $orden->code;
                        break;
                    case 'ORDEN_ATHOS_REVISED': // esto no creo .. ojo
                        if ($to['type_user'] == 'DEPARTAMENT') {
                            $html->assign('link', $url . '/orden/orden/view-detail-orden/id/' . $id_orden);
                        } else {
                            $html->assign('link', $url . '/orden/index/view-detail-orden/id/' . $id_orden);
                        }
                        $html->assign('title_email', "Su Orden fue revisada por nuestra agencia");
                        $bodyText = $html->render('update-status.phtml');
                        $subject = 'su orden fue revisada' . ' / ' . $orden->code;
                        break;
                    case 'ORDEN_ATHOS_COMPLETE': // cliente reviso la orden
                        if ($to['type_user'] == 'DEPARTAMENT') {
                            $html->assign('link', $url . '/orden/orden/view-detail-orden/id/' . $id_orden);
                        } else {
                            $html->assign('link', $url . '/orden/index/view-detail-orden/id/' . $id_orden);
                        }
                        $html->assign('title_email', "Trabajo aprobado por la agencia");
                        $bodyText = $html->render('update-status.phtml');
                        $subject = 'Trabajo aprobado - Orden: ' . ' / ' . $orden->code;
                        break;
                    case 'ORDEN_ATHOS_COMMITED': // entregado por la agencia...
                        if ($to['type_user'] == 'DEPARTAMENT') {
                            $html->assign('link', $url . '/orden/orden/view-detail-orden/id/' . $id_orden);
                        } else {
                            $html->assign('link', $url . '/orden/index/view-detail-orden/id/' . $id_orden);
                        }
                        $html->assign('title_email', "Trabajo entregado");
                        $bodyText = $html->render('update-status.phtml');
                        $subject = 'Trabajo entregado - Orden: ' . ' / ' . $orden->code;
                        break;
                }

                // Email config send
                $mail = new Zend_Mail();
                $mail->addTo($to['email'], $to['name']);
                $mail->setSubject($subject);
                $mail->setBodyHtml($bodyText);
                $mail->send($transport);
            }

            // Reset defaults
            Zend_Mail::clearDefaultFrom();
        }
    }

    private function getEmailDepartamentClientInOrder($id_orden) {
        $orDepDb = new Orden_Model_DbTable_OrdenDepartament();
        $orUserClient = new Orden_Model_DbTable_OrdenUser();
        $userDb = new User_Model_DbTable_User();
        $clientDb = new Client_Model_DbTable_Client();
        $toMails = array();

        // get user client
        $resultRowClient = $orUserClient->fetchRow('id_orden = ' . $id_orden);
        $resultClientAll = $userDb->fetchAll('client_departament=' . $resultRowClient->id_client.' and type="CLIENT"');
        foreach ($resultClientAll as $user) {
            $names = $user->nombre . ' ' . $user->apellidos;
            $toMails[] = array('name' => $names, 'email' => $user->email, 'type_user' => $user->type);
        }

        // get user departament
        $select = $orDepDb->select()->setIntegrityCheck(false)
                ->from(array('od' => 'orden_departament'), array('id', 'id_departament', 'id_orden'))
                ->join(array('d' => 'departament'), "od.id_departament = d.id and od.id_orden = $id_orden")
                ->join(array('u' => 'user'), 'd.id_user = u.id');

        $resultDepartament = $orDepDb->fetchAll($select);
        foreach ($resultDepartament as $user) {
            $names = $user->nombre . ' ' . $user->apellidos;
            $toMails[] = array('name' => $names, 'email' => $user->email, 'type_user' => $user->type);
        }
        //add email statics, include the extract emails from databases   
        //$toMails[] = array('name' => 'Gary Prado', 'email' => 'garypradoruiz@gmail.com');

        return $toMails;
    }

    /*
     * Get data orden Id only a row
     */

    private function getDataOrdenId($id_orden = 0) {
        $ordenDb = new Orden_Model_DbTable_Orden();

        $select = $ordenDb->select()->setIntegrityCheck(false)
                ->from(array('o' => 'orden'), array('id',
                    'code',
                    'title',
                    'description',
                    'create_date',
                    'end_date',
                    'status',
                    'deny_description')
                )->where('o.id=?', $id_orden)
                ->join(array('ou' => 'orden_user'), 'o.id = ou.id_orden')
                ->join(array('u' => 'user'), 'u.id = ou.id_user')
                ->join(array('cl' => 'client'), 'cl.id = u.client_departament', array('name'));

        $row = $ordenDb->fetchRow($select);
        if ($row != null)
            return $row;
        else
            return null;
    }
    
}

?>
